import com.sun.source.tree.Tree;

import java.util.*;

public class BinaryTree {

    static class TreeNode{
        public char val;
        public TreeNode left;
        public TreeNode right;

        public TreeNode(char val){
            this.val=val;
        }
    }

    public TreeNode createTree(){
        TreeNode A=new TreeNode('3');
        TreeNode B=new TreeNode('5');
        TreeNode C=new TreeNode('1');
        TreeNode D=new TreeNode('6');
        TreeNode E=new TreeNode('2');
        TreeNode F=new TreeNode('0');
        TreeNode G=new TreeNode('8');
        TreeNode H=new TreeNode('7');
        TreeNode I=new TreeNode('4');
//        TreeNode J=new TreeNode('4');

        A.left=B;
        A.right=C;
        B.left=D;
        B.right=E;
        C.left=F;
        C.right=G;
        E.left=H;
        E.right=I;

//        A.left=B;
//        A.right=C;
//        B.left=D;
//        B.right=E;
//        C.left=F;
//        C.right=G;
//        E.right=H;

//        A.left=B;
//        A.right=C;
//        B.left=D;
//        B.right=E;
//        C.right=F;
//        D.left=G;
//        D.right=H;
//        G.left=J;
//        F.right=I;

        return A;
    }

    //前序遍历
    public void preOrder(TreeNode root){
        if(root==null) return;
        System.out.print(root.val+" ");
        preOrder(root.left);
        preOrder(root.right);
    }

    //用非遍历进行前序遍历
    public void preOrderNor(TreeNode root){
        if(root == null) return;
        Stack<TreeNode> stack = new Stack<>();
        TreeNode cur = root;

        while (cur!=null || !stack.isEmpty()){
            while (cur!=null){
                stack.push(cur);
                System.out.println(cur.val + " ");
                cur=cur.left;
            }
            TreeNode top = stack.pop();
            cur=top.right;
        }
    }

    //遍历思路
    List<Character> list =new ArrayList<>();
    public List<Character> preorderTraversal(TreeNode root){
        if (root==null) return list;
        System.out.print(root.val+" ");
        list.add(root.val);
        preorderTraversal(root.left);
        preorderTraversal(root.right);
        return list;
    }

    //子问题
    public List<Character> preorderTraversal2(TreeNode root){
        List<Character> list =new ArrayList<>();
        if (root==null) return list;

        list.add(root.val);

        List<Character> leftTree =preorderTraversal2(root.left);
        list.addAll(leftTree);

        List<Character> rightTree = preorderTraversal2(root.right);
        list.addAll(rightTree);

        return list;
    }

    //中序遍历
    public void inOrder(TreeNode root){
        if(root==null) return;
        preOrder(root.left);
        System.out.print(root.val+" ");
        preOrder(root.right);
    }

    //用非遍历进行中序遍历
    public void inOrderNor(TreeNode root) {
        if(root == null) return;
        Stack<TreeNode> stack = new Stack<>();
        TreeNode cur = root;

        while (cur != null || !stack.isEmpty()) {
            while (cur != null) {
                stack.push(cur);
                cur = cur.left;
            }
            TreeNode top = stack.pop();
            System.out.print(top.val + " ");

            cur = top.right;
        }
    }

    //后序遍历
    public void postOrder(TreeNode root){
        if(root==null) return;
        preOrder(root.left);
        preOrder(root.right);
        System.out.print(root.val+" ");
    }

    //用非遍历进行后序遍历
    public void postOrderNor(TreeNode root) {
        if(root == null) return;
        Stack<TreeNode> stack = new Stack<>();
        TreeNode cur = root;
        TreeNode prev = null;
        while (cur != null || !stack.isEmpty()) {
            while (cur != null) {
                stack.push(cur);
                cur = cur.left;
            }
            TreeNode top = stack.peek();
            if (top.right == null || top.right == prev) {
                System.out.print(top.val + " ");
                stack.pop();
                prev = top;
            } else {
                cur = top.right;
            }
        }
    }


    //层序遍历
    public void levelOrder(TreeNode root){
        if (root ==null) return;

        Queue<TreeNode> queue =new LinkedList<>();
        queue.offer(root);

        while (!queue.isEmpty()){
            TreeNode cur = queue.poll();
            System.out.print(cur.val + " ");
            if (cur.left != null){
                queue.offer(cur.left);
            }
            if (cur.right != null){
                queue.offer(cur.right);
            }
        }
        System.out.println();
    }

    //2.0 二维数组，每一行一组
    //https://leetcode.cn/problems/binary-tree-level-order-traversal-ii/
    public List<List<Character>> levelOrder2(TreeNode root){
        List<List<Character>> ret = new ArrayList<>();

        if (root ==null) return ret;

        Queue<TreeNode> queue =new LinkedList<>();
        queue.offer(root);

        while (!queue.isEmpty()){
            int size = queue.size();
            List<Character> list =new ArrayList<>();
            while(size!=0){
                TreeNode cur =queue.poll();
                list.add(cur.val);
                if (cur.left != null){
                    queue.offer(cur.left);
                }
                if (cur.right != null){
                    queue.offer(cur.right);
                }
                size--;
            }
            ret.add(list);
        }
        return ret;
    }

    //https://leetcode.cn/problems/binary-tree-inorder-traversal/
    //二叉树中的中序非递归遍历
    public void inOrder(TreeNode root,List<Character> ret){
        if(root == null) return;

        inOrder(root.left,ret);
        ret.add(root.val);
        inOrder(root.right,ret);

    }
    public List<Character> inorderTraversal(TreeNode root) {
        List<Character> ret = new ArrayList<Character>();
        inOrder(root,ret);
        return ret;
    }

    //https://leetcode.cn/problems/binary-tree-preorder-traversal/
    //二叉树前序非递归遍历
    public List<Character> preorderTraversal3(TreeNode root){
        List<Character> res = new ArrayList<Character>();
        preorder(root, res);
        return res;
    }

    public void preorder(TreeNode root, List<Character> res) {
        if (root == null) {
            return;
        }
        res.add(root.val);
        preorder(root.left, res);
        preorder(root.right, res);
    }

    //判断一棵树是不是完全二叉树 7.16
    public boolean isCompleteTree(TreeNode root){
        if (root == null) return true;

        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);

        while (!queue.isEmpty()){
            TreeNode cur = queue.poll();
            if (cur != null){
                queue.offer(cur.left);
                queue.offer(cur.right);
            }else break;
        }

        while (!queue.isEmpty()){
            TreeNode peek = queue.peek();
            if (peek!=null){
                return false;
            }
            queue.poll();
        }

        return true;
    }

    //https://leetcode.cn/problems/lowest-common-ancestor-of-a-binary-tree/
    //两个节点的公共祖先
    public TreeNode lowestCommonAncestor(TreeNode root,  TreeNode p, TreeNode q){//p,q用来比较两个节点
        if (root == null) return null;

        if (root == p || root ==q) return root;

        TreeNode leftTree = lowestCommonAncestor(root.left,p,q);
        TreeNode rightTree = lowestCommonAncestor(root.right,p,q);

        if (leftTree!=null && rightTree!=null){
            return root;
        }else if(leftTree!=null){
            return leftTree;
        }else return rightTree;
    }

    public boolean getPath(TreeNode root, TreeNode node, Stack<TreeNode> stack){
        if (root == null) return false;

        stack.push(root);
        if(root ==node) return true;

        boolean ret = getPath(root.left,node,stack);
        if (ret) return true;

        ret = getPath(root.right,node,stack);
        if (ret) return true;

        stack.pop();
        return  false;
    }

    //用交叉链表的思想做  计算p，q到第一个节点的长度，然后让长的一个先走

    public TreeNode lowestCommonAncestor2(TreeNode root, TreeNode p, TreeNode q){
        if (root == null) return null;

        //获取路径上的所有节点
        Stack<TreeNode> stackP = new Stack<>();
        Stack<TreeNode> stackQ = new Stack<>();
        getPath(root,p,stackP);

        //比较两个栈的大小，多的出size个
        int sizeP = stackP.size();
        int sizeQ = stackQ.size();
        if(sizeP > sizeQ){
            int size = sizeP-sizeQ;
            while(size!=0){
                stackP.pop();
                size--;
            }
        }else{
            int size = sizeQ - sizeP;
            while (size != 0) {
                stackQ.pop();
                size--;
            }
        }

        //每次看数据 看栈元素是否一样
        while (!stackP.isEmpty() && !stackQ.isEmpty()){
            if (stackP.peek() == stackQ.peek()){
                return stackP.peek();
            }else {
                stackQ.pop();
                stackQ.pop();
            }
        }
        return  null;
    }

    //https://leetcode.cn/problems/construct-string-from-binary-tree/
    //根据二叉树创建字符串
    public String tree2str(TreeNode root){
        if (root == null) return null;

        StringBuilder stringBuilder = new  StringBuilder();
        tree2strChild(root,stringBuilder);
        return stringBuilder.toString();
    }

    public void tree2strChild(TreeNode t,StringBuilder stringBuilder){
        if (t == null) return;
        stringBuilder.append(t.val);

        if (t.left != null){
            stringBuilder.append("(");
            tree2strChild(t.left,stringBuilder);
            stringBuilder.append(")");
        }else {
            if (t.right == null) {
                return;
            }else {
                stringBuilder.append("()");
            }
        }

        if (t.right != null){
            stringBuilder.append("(");
            tree2strChild(t.right,stringBuilder);
            stringBuilder.append(")");
        }else {
            return;
        }
    }



    public static int nodeSize =0;
    //计算树中节点的个数
    public void size(TreeNode root){
        if(root==null) return;

        nodeSize++;
        size(root.left);
        size(root.right);
    }

    public int size2(TreeNode root){
        if (root==null) return 0;

        return size2(root.left)+size2(root.right)+1;
    }

    //获取叶子节点的个数
    public static int leafSize;
    public void getLeafNodeCount(TreeNode root){
        if (root ==null) return;

        if (root.left ==null && root.right==null)
            leafSize++;

        getLeafNodeCount(root.left);
        getLeafNodeCount(root.right);
    }

    public int getLeafNodeCount2(TreeNode root){
        if (root == null) return 0;

        if (root.left==null && root.right==null)
            return 1;

        return getLeafNodeCount2(root.left)+getLeafNodeCount2(root.right);
    }

    //获取第K行的节点数
    public int getKLevelNodeCount(TreeNode root,int k){
        if (root==null) return 0;

        if (k==1) return 1;

        return getKLevelNodeCount(root.left,k-1)+getKLevelNodeCount(root.right,k-1);
    }

//    //获取树的高度
//    public int getHeight(TreeNode root){
//        if (root == null) return 0;
//
//        int leftHigh=getHeight(root.left);
//        int rightHigh=getHeight(root.right);
//
//        //return Math.max(leftHigh,rightHigh)+1;
//        return leftHigh>rightHigh ? leftHigh+1 :rightHigh+1;
//    }

    //在root中找val
    public TreeNode findVal(TreeNode root,char val){
        if (root == null) return null;

        if (root.val==val) return root;

        TreeNode leftT =findVal(root.left,val);
        if (leftT!=null) return leftT;

        TreeNode rightT =findVal(root.right,val);
        if (rightT!=null) return rightT;

        return null;
    }

    //https://leetcode.cn/problems/invert-binary-tree/
    //翻转二叉树
    public TreeNode invertTree(TreeNode root) {
        if(root == null){
            return null;
        }
        if (root.left==null && root.right==null){
            return root;
        }

        TreeNode tmp=root.left;
        root.left=root.right;
        root.right=tmp;

        invertTree(root.left);
        invertTree(root.right);

        return root;
    }

    //https://leetcode.cn/problems/same-tree/
    //相同的树
    public boolean isSameTree(TreeNode p, TreeNode q) {
        //得先检查树的结构是否一样，如果结构不一样就可以直接返回flase
        if (p!=null && q==null || p==null && q!=null){
            return false;
        }
        //如果两个dou为空，则也属于相同的树
        if (p==null && q==null){
            return true;
        }
        //判断值是否一样
        if (p.val != q.val){
            return false;
        }
        //递归
        return isSameTree(p.left,q.left) && isSameTree(p.right,q.right);
    }

    //https://leetcode.cn/problems/symmetric-tree/
    //对称二叉树
    public boolean isSymmetric(TreeNode root) {
        if(root == null) {
            return true;
        }
        return isSymmetricChild(root.left,root.right);
    }

    public boolean isSymmetricChild(TreeNode leftTree,TreeNode rightTree){
        if (leftTree!=null && rightTree==null || leftTree==null && rightTree!=null){
            return false;
        }

        if (leftTree==null && rightTree==null){
            return true;
        }

        if(leftTree.val != rightTree.val) {
            return false;
        }

        return isSymmetricChild(leftTree.left,rightTree.right)
                && isSymmetricChild(leftTree.right,rightTree.left);
    }

    //https://leetcode.cn/problems/subtree-of-another-tree/
    //另一棵树的子树
    public boolean isSubtree(TreeNode root, TreeNode subRoot) {
        if(root == null) {
            return false;
        }
        if(isSameTree(root,subRoot)) return true;
        if(isSubtree(root.left,subRoot))  return true;
        if(isSubtree(root.right,subRoot))  return true;
        return false;
    }

    //获取树的高度
    public int getHeight(TreeNode root){
        if (root == null) return 0;

        int leftHigh=getHeight(root.left);
        int rightHigh=getHeight(root.right);

        //return Math.max(leftHigh,rightHigh)+1;
        return leftHigh>rightHigh ? leftHigh+1 :rightHigh+1;
    }

    //https://leetcode.cn/problems/balanced-binary-tree/
    //判断一棵二叉树是否为平衡二叉树
    public boolean isBalanced(TreeNode root) {//时间复杂度（O(N^2)//因为每次循环都需要重新遍历一遍
        if(root == null) return true;
        int leftHeight = getHeight(root.left);
        int rightHeight = getHeight(root.right);

        return Math.abs(leftHeight-rightHeight) < 2
                && isBalanced(root.left) && isBalanced(root.right);
    }

    //2.0版本
    public boolean isBalanced2(TreeNode root){//时间复杂度O(N)
        if (root == null) return true;
        return getHeight2(root)>=0;
    }

    public int getHeight2(TreeNode root){
        if (root == null) return 0;

        int leftHeight =getHeight2(root.left);
        if (leftHeight < 0) return -1;//只要遍历到下面时，不是平衡二叉树则返回-1，上面就不用再判断了，减少遍历所需要的时间

        int rightHeight =getHeight2(root.right);
        if (rightHeight >= 0 && Math.abs(leftHeight-rightHeight)<=1){
            return Math.max(leftHeight,rightHeight);
        }else
            return -1;
    }


    //https://www.nowcoder.com/practice/4b91205483694f449f94c179883c1fef?tpId=60&&tqId=29483&rp=1&ru=/activity/oj&qru=/ta/tsing-kaoyan/question-ranking
    //二叉树的构建及遍历
    public int i=0;//这里不加static，因为可能下次遍历不会从0开始，而是从上一次遍历所得的i开始
    public TreeNode createTree(String str){
        TreeNode root =null;
        if(str.charAt(i)!='#'){
            root=new TreeNode(str.charAt(i));
            i++;
            root.left=createTree(str);
            root.right=createTree(str);
        }else
            i++;
        return root;
    }


    //二叉搜索树与双向链表
    //7-14  2:16

    TreeNode prev=null;

    public TreeNode Convert(TreeNode pRootOfTree){
        if (pRootOfTree==null) return null;

        ConvertChild(pRootOfTree);
        TreeNode head=pRootOfTree;
        while (head.left!=null){
            head=head.left;
        }
        return head;
    }

    public void ConvertChild(TreeNode root){
        if (root ==null){
            return;
        }
        ConvertChild(root.left);
        //打印
        root.left =prev;
        if (prev!=null){
            prev.right=root;
        }
        prev=root;
        ConvertChild(root.right);
    }

}
